<!-- tableDetail.vue -->
<template>
    <div class="container">
        <!-- 显示桌子的历史记录 -->
        <div v-if="table" v-for="record in tableRecords" :key="record.id" class="record-item">
            <p class="record-label">开始时间: {{ record.startTime }}</p>
            <p class="record-label">结束时间: {{ record.endTime || '未结束' }}</p>
            <p class="record-label">实收金额: {{ record.actualAmount }}</p>
            <p class="record-label">预收金额: {{ record.preAmount }}</p>
        </div>
        <!-- 当桌子状态为空置时，显示开始时间选择器、单价选择框和开桌按钮 -->
        <div v-if="table && tableStatus === '空置'" class="action-section">
            <div class="date-time-container">
                <label class="input-label">开始时间:</label>
                <picker mode="date" :value="dateIndex" :start="minDate" :end="maxDate" @change="onDateChange">
                    <view class="picker input-field">{{ selectedDate }}</view>
                </picker>
                <picker mode="time" :value="timeIndex" @change="onTimeChange">
                    <view class="picker input-field">{{ selectedTime }}</view>
                </picker>
            </div>
            <label class="input-label">单价 (元/时):</label>
            <select v-model="unitPrice" class="input-field beautify-select">
                <option v-for="price in priceOptions" :key="price" :value="price">{{ price }}</option>
            </select>
            <button @click="startTable" class="action-button">开桌</button>
        </div>
        <!-- 当桌子状态不为空置时，显示结束时间选择器、实收金额输入框、预收金额显示和结束按钮 -->
        <div v-if="table && tableStatus!== '空置'" class="action-section">
            <label class="input-label">选择结束时间:</label>
            <picker mode="time" :value="endTimeIndex" @change="onEndTimeChange">
                <view class="picker input-field">{{ endTime }}</view>
            </picker>
            <label class="input-label">实收金额:</label>
            <input type="number" v-model="actualAmount" placeholder="请输入实收金额" class="input-field">
            <p class="record-label">预收金额: {{ preAmount.toFixed(2) }}</p>
            <button @click="endTable" class="action-button">结束</button>
        </div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'vuex';
import { onLoad, onShow } from '@dcloudio/uni-app';

const store = useStore();
let tableId = null;

onLoad((options) => {
    tableId = parseInt(options.tableId);
});

const currentStore = computed(() => store.state.currentStore);

const table = computed(() => {
    if (currentStore.value) {
        return currentStore.value.tables.find(table => table.id === tableId);
    }
    return null;
});

const tableRecords = computed(() => {
    if (table.value) {
        return table.value.records;
    }
    return [];
});

const tableStatus = computed(() => {
    if (table.value) {
        return table.value.status;
    }
    return null;
});

// 初始化选择的日期为当前日期
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const selectedDate = ref(`${year}-${month}-${day}`);
// 初始化选择的时间为当前时间
const hours = String(today.getHours()).padStart(2, '0');
const minutes = String(today.getMinutes()).padStart(2, '0');
const selectedTime = ref(`${hours}:${minutes}`);
const endTime = ref(selectedTime.value);
const unitPrice = ref(15); // 默认单价 15 元/时
const actualAmount = ref('');
const preAmount = ref(0);

// 生成日期选择范围，这里简单设置为当前日期前后一个月
const minDate = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
const maxDate = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];

const dateIndex = ref(0);
const timeIndex = ref(0);
const endTimeIndex = ref(0);

// 生成单价选项数组，范围 0 - 30
const priceOptions = Array.from({ length: 31 }, (_, i) => i);

const onDateChange = (e) => {
    selectedDate.value = e.detail.value;
    dateIndex.value = e.detail.value;
};

const onTimeChange = (e) => {
    selectedTime.value = e.detail.value;
    timeIndex.value = e.detail.value;
};

const onEndTimeChange = (e) => {
    endTime.value = e.detail.value;
    endTimeIndex.value = e.detail.value;
    calculatePreAmount();
};

const calculatePreAmount = () => {
    if (table.value) {
        const startTimeStr = table.value.records[table.value.records.length - 1].startTime;
        const [startDatePart, startTimePart] = startTimeStr.split(' ');
        const [startHours, startMinutes] = startTimePart.split(':');
        const [endHours, endMinutes] = endTime.value.split(':');

        let endDate = new Date(startDatePart);
        if (parseInt(endHours) < parseInt(startHours) || (parseInt(endHours) === parseInt(startHours) && parseInt(endMinutes) < parseInt(startMinutes))) {
            endDate.setDate(endDate.getDate() + 1);
        }

        const endYear = endDate.getFullYear();
        const endMonth = String(endDate.getMonth() + 1).padStart(2, '0');
        const endDay = String(endDate.getDate()).padStart(2, '0');
        const endDateTime = `${endYear}-${endMonth}-${endDay} ${endTime.value}`;

        // 计算使用时长（小时）
        const startDateTime = new Date(`${startDatePart} ${startTimePart}`);
        const endDateTimeObj = new Date(endDateTime);
        const duration = (endDateTimeObj - startDateTime) / (1000 * 60 * 60);

        // 计算预收金额
        preAmount.value = duration * unitPrice.value;
    }
};

const startTable = () => {
    if (table.value) {
        // 组合选择的日期和时间为完整的开始时间
        const startTime = `${selectedDate.value} ${selectedTime.value}`;
        // 提交开桌操作到 store，传递 tableId、开始时间和单价
        store.commit('startTable', { tableId, startTime, unitPrice: unitPrice.value });
        // 返回首页
        uni.navigateBack({
            delta: 1,
            success: () => {
                console.log('返回首页成功');
            },
            fail: (err) => {
                console.error('返回首页失败', err);
            }
        });
    }
};

const endTable = () => {
    if (table.value) {
        calculatePreAmount();
        // 若实收金额为空或为 0，则将其设为预收金额
        if (!actualAmount.value || parseFloat(actualAmount.value) === 0) {
            actualAmount.value = preAmount.value.toString();
        }
        // 提交结束操作到 store，传递 tableId、结束时间、预收金额和实收金额
        store.commit('endTable', {
            tableId,
            endTime: `${selectedDate.value} ${endTime.value}`,
            preAmount: preAmount.value,
            actualAmount: parseFloat(actualAmount.value)
        });
        uni.navigateBack();
    }
};

onShow(() => {
    if (table.value && tableStatus.value!== '空置') {
        calculatePreAmount();
    }
});
</script>

<style scoped>
.container {
    padding: 20px;
    background-color: #f4f4f4;
    font-family: Arial, sans-serif;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    max-width: 600px;
    margin: 0 auto;
}

.record-item {
    border: 1px solid #ccc;
    padding: 15px;
    margin: 15px 0;
    background-color: #fff;
    border-radius: 6px;
}

.record-label {
    margin: 5px 0;
    color: #333;
}

.action-section {
    margin-top: 20px;
    background-color: #fff;
    padding: 20px;
    border-radius: 6px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.05);
}

.date-time-container {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.input-label {
    margin-right: 10px;
    font-weight: bold;
    color: #555;
}

.input-field {
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-right: 10px;
    flex: 1;
}

.picker {
    display: inline-block;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-left: 10px;
    background-color: #fff;
}

.action-button {
    padding: 10px 20px;
    background-color: #007BFF;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.action-button:hover {
    background-color: #0056b3;
}

.beautify-select {
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    background-image: url('data:image/svg+xml;utf8,<svg fill="%23555" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/><path d="M0 0h24v24H0z" fill="none"/></svg>');
    background-repeat: no-repeat;
    background-position: right 10px center;
    background-size: 16px;
    padding-right: 30px;
    transition: border-color 0.3s ease;
}

.beautify-select:hover {
    border-color: #007BFF;
}

.beautify-select:focus {
    outline: none;
    border-color: #007BFF;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}
</style>    